package com.ylw.util;

import com.ylw.project.handler.Handler;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class Config {

    private final static Logger logger = Logger.getLogger(Config.class);

    private final static Properties config = new Properties();

    static {
        loadProperties();
    }

    /**
     * 获取handlers类对象
     *
     * @return
     */
    public static List<Handler> getHandlersClass() {
        List<Handler> handlers = new ArrayList();
        try {
            String s = config.getProperty("project.handler");
            List sHandlers = getPropertValue("project.handler");
            logger.info("handlers class is " + s);
            for (Object temp : sHandlers) {
                Class clazz = Class.forName(temp.toString());
                handlers.add((Handler) clazz.newInstance());
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return handlers;
    }


    /**
     * 获取config.properties文件里的值
     *
     * @param key
     * @return
     */
    public static List getPropertValue(String key) {
        List result = new ArrayList();
        String s = config.getProperty(key);
//        if (StringUtils.isNotBlank(s)) {
        if (s!=null && s.length()!=0) {
            String[] ss = s.split(config.getProperty("project.split"));
            result = Arrays.asList(ss);
        }
        return result;
    }

    /**
     * 加载配置文件
     */
    private static void loadProperties() {
        InputStream in = ClassLoader.getSystemClassLoader().
                getResourceAsStream("config.properties");
        try {
            config.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        System.out.println(getPropertValue("project.source.java.root"));

        getHandlersClass();
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();

        InputStream in = classLoader.getResourceAsStream("config.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            String s = p.getProperty("project.handler");
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
